package com.lingshu.app.ui.register;

import android.content.Context;

import androidx.lifecycle.MutableLiveData;

import com.lingshu.app.base.BaseViewModel;
import com.lingshu.app.config.App;
import com.lingshu.app.config.Constants;
import com.lingshu.app.config.LoadState;
import com.lingshu.app.model.enums.ImagePart;
import com.lingshu.app.model.enums.ScreeningType;
import com.lingshu.app.model.register.RegisterImageResponse;
import com.lingshu.app.model.register.RegisterQueryRequest;
import com.lingshu.app.model.register.RegisterResponse;
import com.lingshu.app.model.register.RegisterScreenshotDeleteRequest;
import com.lingshu.app.model.register.RegisterScreenshotResponse;
import com.lingshu.app.network.CustomDisposable;
import com.lingshu.app.network.RetrofitMobileClient;
import com.lingshu.app.repository.ScreeningRegisterRepository;
import com.lingshu.app.service.DownloadManager;
import com.lingshu.app.service.RegisterService;
import com.lingshu.app.utils.PathUtils;
import com.lingshu.core.utils.KLog;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import javax.inject.Inject;

import cn.hutool.core.io.FileUtil;
import dagger.hilt.android.lifecycle.HiltViewModel;
import retrofit2.HttpException;

/**
 * @author 于定金
 * @version 1.0
 * @Date 2024/1/3 14:15
 * @Description
 */
@HiltViewModel
public class RegisterViewModel extends BaseViewModel {
    private static String TAG = RegisterViewModel.class.getName();
    /**
     * 是否显示
     */
    public MutableLiveData<Boolean> showFlag = new MutableLiveData<>();

    /**
     * 筛查记录信息
     */
    public MutableLiveData<RegisterResponse> register = new MutableLiveData<>();

    /**
     * 筛查影像集合
     */
    public MutableLiveData<List<RegisterImageResponse>> imageList = new MutableLiveData<>();

    /**
     * 当前选择的影像
     */
    public MutableLiveData<RegisterImageResponse> selectedImage = new MutableLiveData<>();

    /**
     * 保存截图结果
     */
    public MutableLiveData<RegisterScreenshotResponse> screenshot = new MutableLiveData<>();

    /**
     * 筛查截图集合
     */
    public MutableLiveData<List<RegisterScreenshotResponse>> screenshotList = new MutableLiveData<>();

    /**
     * 选中的筛查截图集合
     */
    public MutableLiveData<List<RegisterScreenshotResponse>> screenshotSelectedList = new MutableLiveData<>();

    /**
     * 大图路径
     */
    public MutableLiveData<String> selectedImageLocalPath = new MutableLiveData<>();

    /**
     * 图片帧
     */
    public MutableLiveData<Integer> selectedImageCurrentFrame = new MutableLiveData<>();

    /**
     * 查询条件
     */
    public MutableLiveData<RegisterQueryRequest> registerQueryRequest = new MutableLiveData<>();

    //是否向左偏移
    public MutableLiveData<Boolean> leftOffset = new MutableLiveData<>();

    private ScreeningRegisterRepository registerRepository;

    @Inject
    RegisterViewModel(ScreeningRegisterRepository registerRepository) {
        this.registerRepository = registerRepository;
    }

    /**
     * 数据初始化
     */
    @Override
    public void initData() {
        if (showFlag.getValue() == null) {
            showFlag.postValue(false);
        }
        if (leftOffset.getValue() == null) {
            leftOffset.postValue(true);
        }
        List<ScreeningType> screeningTypeList = new ArrayList<>();
        screeningTypeList.add(ScreeningType.THYROID);
        screeningTypeList.add(ScreeningType.CAROTID);
        screeningTypeList.add(ScreeningType.BREAST);
        RegisterQueryRequest queryRequest = new RegisterQueryRequest(screeningTypeList, App.getMvUtils().getLong(Constants.USER_ID), null, 1, 1);
        //RegisterQueryRequest queryRequest = new RegisterQueryRequest(null, null, 1, 1);
        registerQueryRequest.postValue(queryRequest);
        CustomDisposable.addDisposable(RetrofitMobileClient.getInstance().getService(RegisterService.class).getRegisterList(queryRequest), returnObject -> {
            if (returnObject.isSuccess() && returnObject.getData() != null) {
                register.postValue(returnObject.getData().getRegister());
                if (returnObject.getData().getImageList() != null && returnObject.getData().getImageList().size() > 0)
                    imageList.postValue(returnObject.getData().getImageList());
                if (returnObject.getData().getScreenshotList() != null && returnObject.getData().getScreenshotList().size() > 0)
                    screenshotList.postValue(returnObject.getData().getScreenshotList());
                showFlag.postValue(true);
            } else {
                loadState.postValue(LoadState.NO_DATA);
            }
        }, throwable -> {
            HttpException exception = (HttpException) throwable;
            if (exception.code() == 401) {
                tokenIsValid.postValue(false);
            } else {
                KLog.e(TAG, throwable.getMessage());
                //infoMsg.postValue(throwable.getMessage());
                loadState.postValue(LoadState.NO_DATA);
            }
        });

        if (screenshotList.getValue() == null) {
            List<RegisterScreenshotResponse> list = new ArrayList<>();
            screenshotList.postValue(list);
        }
        if (screenshotSelectedList.getValue() == null) {
            List<RegisterScreenshotResponse> list = new ArrayList<>();
            screenshotSelectedList.postValue(list);
        }
    }

    /**
     * 将截图添加到集合中
     *
     * @param screenshot
     */
    public void addScreenshotToCollection(RegisterScreenshotResponse screenshot) {
        List<RegisterScreenshotResponse> list = screenshotList.getValue();
        list.add(screenshot);
        screenshotList.postValue(list);
    }

    /**
     * 添加报告截图
     *
     * @param screenshotResponse
     * @return
     */
    public boolean addSelectedScreenshot(RegisterScreenshotResponse screenshotResponse) {
        if (screenshotResponse.getParts() == null || screenshotResponse.getParts() == ImagePart.NONE)
            return false;
        List<RegisterScreenshotResponse> list = screenshotSelectedList.getValue();
        List<RegisterScreenshotResponse> queryList = list.stream().filter(e -> e.getParts() == screenshotResponse.getParts()).collect(Collectors.toList());
        if (queryList.size() == 0) {
            if (list.size() < 2) {
                screenshotSelectedList.getValue().add(screenshotResponse);
                return true;
            }
        } else {
            if (queryList.stream().anyMatch(e -> e.getId() == screenshotResponse.getId())) {
                screenshotSelectedList.getValue().remove(screenshotResponse);
                return true;
            }
            return false;
        }
        return false;
    }

    /**
     * 删除截图
     *
     * @param item
     * @param processor
     */
    public void removeScreenshot(RegisterScreenshotResponse item, Consumer<RegisterScreenshotResponse> processor) {
        if (item != null) {
            RegisterScreenshotDeleteRequest request = new RegisterScreenshotDeleteRequest();
            request.setScreenshotId(item.getId());
            request.setRegisterId(item.getRegisterId());
            request.setApplyNo(this.register.getValue().getApplyNo());
            CustomDisposable.addDisposable(RetrofitMobileClient.getInstance().getService(RegisterService.class).removeScreenshot(request), returnObject -> {
                if (returnObject.isSuccess()) {
                    this.screenshotList.getValue().remove(item);
                    if (processor != null) processor.accept(item);
                } else {
                    infoMsg.postValue(returnObject.getMessage());
                }
            }, throwable -> {
                KLog.e(TAG, throwable.getMessage());
                infoMsg.postValue(throwable.getMessage());
            });
        }
    }

    /**
     * 选择影像
     *
     * @param image
     */
    public void setDicomSelected(RegisterImageResponse image) {
        List<RegisterImageResponse> list = imageList.getValue();
        if (list != null) {
            list.stream().forEach(c -> {
                if (c.getId() == image.getId()) {
                    c.setIsSelected(true);
                    selectedImage.postValue(c);
                } else {
                    c.setIsSelected(false);
                }
            });
        }
    }

    /**
     * 拷贝文件
     *
     * @param sourceFilePath
     * @param destinationFilePath
     * @return
     */
    public boolean copyFile(String sourceFilePath, String destinationFilePath) {
        File sourceFile = new File(sourceFilePath);
        if (!sourceFile.exists()) return false;
        PathUtils.checkDirectory(destinationFilePath);
        try (InputStream inputStream = new FileInputStream(sourceFilePath); OutputStream outputStream = new FileOutputStream(destinationFilePath)) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }
            return true; // 拷贝成功
        } catch (IOException e) {
            e.printStackTrace();
            return false; // 拷贝失败
        }
    }

    /**
     * 下载压缩文件
     *
     * @param itemData
     * @param downloadFlag
     * @param context
     */
    public void downloadImage(RegisterImageResponse itemData, boolean downloadFlag, Context context) {
        File fileDirectory = new File(context.getExternalCacheDir(), "/temp/dicom/" + new SimpleDateFormat("yyyy-MM-dd", Locale.CHINESE).format(register.getValue().getCreateTime()) + "/" + itemData.getRegisterId() + "/" + itemData.getId());
        if (!fileDirectory.exists()) {
            if (downloadFlag) {
                itemData.setShowLoading(true);
                String zipPath = fileDirectory + ".zip";
                CustomDisposable.addDisposable(new DownloadManager().downloadImage(itemData.getId(), zipPath), s -> {
                    itemData.setShowLoading(false);
                    itemData.setCanDownload(false);
                    itemData.setCanPlay(true);
                    itemData.setLocalPath(fileDirectory.getAbsolutePath() + "/0.jpeg");
                    selectedImageLocalPath.postValue(itemData.getLocalPath());
                    selectedImageCurrentFrame.postValue(1);
                }, throwable -> {
                    KLog.e(TAG, throwable.getMessage());
                    infoMsg.postValue(throwable.getMessage());
                });
            } else {
                itemData.setLocalPath(fileDirectory.getAbsolutePath() + "/0.jpeg");
            }
        } else {
            itemData.setCanDownload(false);
            itemData.setCanPlay(true);
            itemData.setLocalPath(fileDirectory.getAbsolutePath() + "/0.jpeg");
        }
    }

    /**
     * 下载截图
     *
     * @param screenshotResponse
     * @param downloadFlag
     * @param usedFlag
     * @param context
     */
    public void downloadScreenshot(RegisterScreenshotResponse screenshotResponse, boolean downloadFlag, boolean usedFlag, Context context) {
        File file = new File(context.getExternalCacheDir(), "/temp/screenshot/" + new SimpleDateFormat("yyyy-MM-dd", Locale.CHINESE).format(register.getValue().getCreateTime()) + "/" + screenshotResponse.getRegisterId() + "/" + screenshotResponse.getImageId() + "_" + screenshotResponse.getCurrentFrame().toString() + PathUtils.getExtension(screenshotResponse.getStoragePath()));
        if (!file.exists()) {
            if (downloadFlag) {
                CustomDisposable.addDisposable(new DownloadManager().downloadScreenshot(screenshotResponse.getId(), file.getAbsolutePath()), fileInfo -> {
                    screenshotResponse.setIsUsedToReport(usedFlag);
                    screenshotResponse.setCanDownloadFlag(false);
                    screenshotResponse.setLocalStoragePath(fileInfo.getAbsolutePath());
                }, throwable -> {
                    KLog.e(TAG, throwable.getMessage());
                    infoMsg.postValue(throwable.getMessage());
                });
            }
        } else {
            screenshotResponse.setCanDownloadFlag(false);
            screenshotResponse.setIsUsedToReport(false);
            screenshotResponse.setLocalStoragePath(file.getAbsolutePath());
        }
    }

    /**
     * 图像集合初始化
     *
     * @param list
     * @param context
     */
    public void imageListInit(List<RegisterImageResponse> list, Context context) {
        for (RegisterImageResponse imageResponse : list) {
            downloadImage(imageResponse, false, context);
            if (FileUtil.exist(imageResponse.getLocalPath()) && selectedImage.getValue() == null) {
                selectedImage.postValue(imageResponse);
            } else if (imageResponse.getCanDownload() && selectedImage.getValue() == null) {
                selectedImage.postValue(imageResponse);
            }
        }
    }

    /**
     * 截图集合初始化
     *
     * @param list
     * @param context
     */
    public void screenshotListInit(List<RegisterScreenshotResponse> list, Context context) {
        for (RegisterScreenshotResponse screenshotResponse : list) {
            File file = new File(context.getExternalCacheDir(), "/temp/screenshot/" + new SimpleDateFormat("yyyy-MM-dd", Locale.CHINESE).format(register.getValue().getCreateTime()) + "/" + screenshotResponse.getRegisterId() + "/" + screenshotResponse.getImageId() + "_" + screenshotResponse.getCurrentFrame().toString() + PathUtils.getExtension(screenshotResponse.getStoragePath()));
            if (screenshotResponse.getAutoDownload()) {
                if (file.exists()) {
                    screenshotResponse.setLocalStoragePath(file.getAbsolutePath());
                    screenshotResponse.setIsUsedToReport(true);
                } else {
                    downloadScreenshot(screenshotResponse, true, true, context);
                }
                screenshotSelectedList.getValue().add(screenshotResponse);
            } else {
                if (file.exists()) {
                    screenshotResponse.setLocalStoragePath(file.getAbsolutePath());
                    screenshotResponse.setIsUsedToReport(false);
                    screenshotResponse.setCanDownloadFlag(false);
                }else{
                    screenshotResponse.setIsUsedToReport(null);
                    screenshotResponse.setCanDownloadFlag(true);
                }
            }
        }
    }
}
